package com.iris.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;

public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        channel.configureBlocking(false);
        channel.socket().bind(new InetSocketAddress("localhost",8889));
        channel.register(selector, SelectionKey.OP_ACCEPT);
        while(true){
            selector.select();
            Set<SelectionKey> sets = selector.selectedKeys();
            if(sets!=null&&sets.size()>0){
                for (SelectionKey set : sets) {
                    if(set.isValid()){
                        sets.remove(set);
                        if(set.isReadable()){
                            SocketChannel sc = (SocketChannel) set.channel();
                            System.out.println(sc.hashCode()+"==="+sc.toString()+"==="+sc);
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int readBytes = sc.read(buffer);

                            if(readBytes>-1){
                                byte[] bytes = buffer.array();
                                System.out.println("服务端收到信息：" + new String(bytes));
                            }
                            System.out.println("fasongxiaoxi");
                            String response = "服务端反馈的消息="+new String(buffer.array());
                            ByteBuffer buffer1 = ByteBuffer.allocate(response.getBytes().length);
                            buffer1.put(response.getBytes());
                            buffer1.flip();
                            sc.write(buffer1);
                        }else if (set.isAcceptable()){
                            SelectableChannel selectableChannel = set.channel();
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectableChannel;
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            socketChannel.close();
                        }
                    }
                }
            }
        }
    }
}
